package main

import (
	"crypto/md5"
	"database/sql"
	"encoding/json"
	"fmt"
	"net"
)

var db *sql.DB
var err error

type userList struct {
	id      int
	user_id int
	own_id  int
}

//密码错误 = 1
//已经在线 = 2
//允许登录 = 3
type ansStruct struct {
	AnswerStatus int
	AnswerData   string
}

func init() () {
	db, err = sql.Open("mysql", "root:123456@tcp(localhost:3306)/chat_room?charset=utf8")
	if err != nil {
		fmt.Println("get link DbFail...", err)
		return
	}
}

func doLogin(con net.Conn, info loginInfo) {
	//根据账号密码查询
	var dbIfon loginInfo
	transErr := db.QueryRow("SELECT * FROM USER WHERE NUMBER = ?", info.Number).Scan(&dbIfon.Id, &dbIfon.Number, &dbIfon.Password, &dbIfon.Status)

	var answerStatus int
	var answerData string

	if transErr != nil {
		fmt.Println("convert entity err", err)
		return
	}
	password := md5.Sum([]byte(info.Password))
	if string(password[:]) != dbIfon.Password {
		answerStatus = 1
		return
	}

	if dbIfon.Status == 1 {
		answerStatus = 2
		return
	}
	answerStatus = 3

	//get this user's userList
	var friendsList []userList
	rows, err := db.Query("SELECT * FROM user_list WHERE user_id = ? ", dbIfon.Id)
	if err != nil {
		fmt.Println("find user's userList fail", err)
		return
	}
	for rows.Next() {
		var uList userList
		err := rows.Scan(&uList.id, &uList.user_id, &uList.own_id)
		if err != nil {
			fmt.Println("convert user list to entity err", err)
		}
		friendsList = append(friendsList, uList)
	}

	friends := make([]loginInfo, 10)

	for i := 0; i < len(friendsList); i++ {
		var u loginInfo
		db.QueryRow("SELECT * FROM USER WHERE id = ? AND status != 1", friendsList[i].user_id).Scan(&u.Id,
			u.Number, u.Password, u.Status)
		friends = append(friends, u)
	}
	friJson, err := json.Marshal(friends)
	if err != nil {
		fmt.Println("friends list to json err", err)
		return
	}
	answerData = string(friJson)
	var result ansStruct = ansStruct{
		AnswerStatus:answerStatus,
		AnswerData:answerData,
	}
	resJson, err := json.Marshal(result)
	if err != nil {
		fmt.Println("answer struct to json err", err)
		return
	}
	con.Write(resJson)
}
